/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tableModel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.table.AbstractTableModel;
import modelo.Motorista;

/**
 *
 * @author Marcio
 */
public class MotoristaTM extends AbstractTableModel {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("FrotasPU");
    private List listaIds;
    private ArrayList<Motorista> lista = new ArrayList();

    public MotoristaTM() {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        listaIds = em.createQuery("SELECT m.id FROM Motorista m").getResultList();

        for (int i = 0; i < listaIds.size(); i++) {
            Motorista mot = (Motorista) listaIds.get(i);
            lista.add((Motorista) em.createNamedQuery("Motorista.findById").setParameter("id", mot.getId().toString()).getSingleResult());
        }
       // for (Iterator<String> it = listaIds.iterator(); it.hasNext();) {
       //     String elem = it.next();
        //    lista.add((Motorista) em.createNamedQuery("Motorista.findById").setParameter("id", elem).getSingleResult());
      //  }

        em.close();

    }

    @Override
    public int getRowCount() {
        return lista.size();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return lista.get(rowIndex).getId();
        }else if (columnIndex == 1){
            return lista.get(rowIndex).getNome();
        }
        return null;
    }
    
    @Override
    public void setValueAt(Object value, int row, int col) {  
          Motorista dado = lista.get(row);  
          switch (col){  
               case 0: dado.setId((Integer)value); break;  
               case 1: dado.setNome((String)value); break; 
          }  
          fireTableCellUpdated(row, col);  
       }  
}
